import React, {Component} from 'react';
import {Button, Form, Input, Row, Col, Table, Pagination, DatePicker, Select} from 'antd';
import moment from 'moment';
import {EditOrders} from '../components/EditComponent';
import {outbound} from "../value";
import app from '../AppMethod';
import {Consumer, Provider} from "../store";

const FormItem = Form.Item;
const RangePicker = DatePicker.RangePicker;
const Option = Select.Option;

class storageManage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            pagination: {
                current: 0,
                total: 0,
                pagination: 0
            },
            allPage: 0,
            data: [],
            searchData: {}
        }
    };

    columns = [
        {
            title: '订单号',
            dataIndex: 'output_num'
        },
        {
            title: '客户名',
            width: '200px',
            dataIndex: 'customer_name'
        },
        {
            title: '下单日期',
            dataIndex: 'output_order_time'
        },
        {
            title: '订单金额',
            dataIndex: 'output_money'
        },
        {
            title: '应收款',
            dataIndex: 'output_need_money'
        },
        {
            title: '已收款',
            dataIndex: 'output_real_money'
        },
        {
            title: '交货日期',
            dataIndex: 'output_delivery_time'
        },
        {
            title: '件数',
            dataIndex: 'output_package'
        },
        {
            title: '实际件数',
            dataIndex: 'output_real_package'
        },
        {
            title: '散包数',
            dataIndex: 'output_single'
        },
        {
            title: '实际散包数',
            dataIndex: 'output_real_single'
        },
        {
            title: '实际散件数',
            dataIndex: 'output_real_parts'
        },
        {
            title: '状态',
            dataIndex: 'output_status',
            render: output_status => {
                let text;
                if (output_status == 0) {
                    text = '待接单';
                } else if (output_status == 1) {
                    text = '已接单';
                } else if (output_status == 2) {
                    text = '配货中';
                } else if (output_status == 3) {
                    text = '待对货'
                } else if (output_status == 4) {
                    text = '待配送'
                } else if (output_status == 5) {
                    text = '待改单'
                } else if (output_status == 6) {
                    text = '配送中'
                } else if (output_status == 7) {
                    text = '已完成'
                }
                return (
                    <span>{text}</span>
                )
            }
        },
        {
            title: '操作',
            dataIndex: this.columns,
            render: data => {
                return (
                    <span>
                        <EditOrders data={data} handleRefresh={() => this.handleAfterEdit()}/>
                        <span style={{color: '#1890ff', cursor: 'pointer', marginLeft: '10px'}}
                              onClick={() => this.handleGetDetail(data.output_id)}>{'详情'}</span>
                    </span>
                )
            }
        }
    ];

    render() {
        return (
            <div>
                <Row>
                    <SearchLists
                        clickSearch={(value) => {
                            this.handleGetSearch(value)
                        }}
                        handleReset={() => this.handleReset()}
                        orderStatus={this.props.orderStatus}
                    >
                    </SearchLists>
                </Row>
                <Row style={{marginTop: '20px'}}>
                    <Table
                        columns={this.columns}
                        rowKey={record => record.output_id}
                        loading={this.state.loading}
                        dataSource={this.state.data}
                        pagination={false}
                    >
                    </Table>
                </Row>
                <Row style={{marginTop: '20px'}}>
                    <Col span={12} style={{fontSize: '15px'}}>
                        共 {this.state.pagination.total} 条记录 第 {this.state.pagination.current} / {this.state.allPage}
                        页
                    </Col>
                    <Col span={12} style={{textAlign: 'right'}}>
                        <Pagination {...this.state.pagination} showSizeChanger={true} showQuickJumper={true}
                                    hideOnSinglePage={false}
                                    onChange={(page, pageSize) => this.handlePageChange(page, pageSize)}
                                    onShowSizeChange={(current, size) => this.handleSizeChange(current, size)}/>
                    </Col>
                </Row>
            </div>
        )
    };

    componentDidMount() {
        const {orderStatus, dispatch} = this.props;//获取订单管理的上下文状态
        dispatch({menuType: "订单管理"});
        this.handleSearchOrderList(orderStatus);
    };

    componentWillUnmount() {
        this.setState = (count, callback) => {
            return;
        }
    }

    /**
     * 根据搜索条件查询订单
     * @param value
     */
    handleGetSearch(value) {
        let times = value.order_time;
        let order_time_start = undefined;
        let order_time_end = undefined;
        if (times != undefined && times.length > 0) {
            order_time_start = moment(times[0]._d).format('YYYY-MM-DD');
            order_time_end = moment(times[1]._d).format('YYYY-MM-DD');
        }
        let times1 = value.delivery_time;
        let delivery_time_start = undefined;
        let delivery_time_end = undefined;
        if (times1 != undefined && times1.length > 0) {
            delivery_time_start = moment(times1[0]._d).format('YYYY-MM-DD');
            delivery_time_end = moment(times1[1]._d).format('YYYY-MM-DD');
        }
        let tempData = {
            output_num: value.output_num,
            output_status: value.output_status,
            customer_name: value.customer_name,
            order_time_start: order_time_start,
            order_time_end: order_time_end,
            delivery_time_start: delivery_time_start,
            delivery_time_end: delivery_time_end
        };
        console.log(tempData);
        this.setState({searchData: tempData});
        let searchData = tempData;
        searchData.page = 1;
        searchData.size = this.state.pagination.pageSize || 10;
        this.handleSearchOrderList(searchData);
    };

    /**
     * 处理重置事件
     */
    handleReset() {
        this.setState({searchData: {}});
        this.handleSearchOrderList();
    };

    /**
     * 确认处理后查询订单列表
     */
    handleAfterEdit() {
        let data = this.state.searchData;
        data.page = this.state.pagination.current ? this.state.pagination.current : 1;
        data.size = this.state.pagination.pageSize ? this.state.pagination.pageSize : 10;
        this.handleSearchOrderList(data);
    }

    /**
     * 获取订单列表事件
     * @param data
     */
    handleSearchOrderList(data = {page: 1, size: 10}) {
        const {dispatch} = this.props;
        this.setState({loading: true});
        app.post(outbound.SEARCH_OUTPUTLIST, data).then((result) => {
            if (result.code === 1) {
                let count = result.data.count;
                let pagination = {
                    current: data.page,
                    pageSize: data.size,
                    total: count
                };
                let allPage;
                if (count % data.size > 0) {
                    allPage = parseInt(count / data.size) + 1;
                } else {
                    allPage = count / data.size;
                }
                let orderData = result.data.dataSet;
                for (let i = 0; i < orderData.length; i++) {
                    orderData[i].output_delivery_time = orderData[i].output_delivery_time === null ? '' : moment(orderData[i].output_delivery_time).format('YYYY-MM-DD');
                    orderData[i].output_order_time = orderData[i].output_order_time === null ? '' : moment(orderData[i].output_order_time).format('YYYY-MM-DD');
                }
                dispatch({orderStatus: data});//保存到上下文
                this.setState({allPage, pagination, data: orderData, loading: false});
            } else {
                let pagination = {
                    current: 0,
                    pageSize: 0,
                    total: 0
                };
                let allPage = 0;
                this.setState({allPage, pagination, data: [], loading: false});
            }
        })
    };

    /**
     * 处理分页跳转事件
     * @param page
     * @param size
     */
    handlePageChange(page, size) {
        let data = this.state.searchData;
        data.page = page;
        data.size = size;
        this.handleSearchOrderList(data);
    };

    /**
     * 处理页数变化事件
     * @param current
     * @param size
     */
    handleSizeChange(current, size) {
        let data = this.state.searchData;
        data.page = current;
        data.size = size;
        this.handleSearchOrderList(data);
    };

    /**
     * 处理跳转到详情页面
     * @param id
     */
    handleGetDetail(id) {
        this.props.history.push('/index/orderDetails/' + id);
    }

};

class SearchList extends Component {
    constructor(props) {
        super(props);
        this.state = {}
    };

    formItemLayout = {
        labelCol: {span: 8},
        wrapperCol: {span: 12},
    };

    render() {
        const {getFieldDecorator} = this.props.form;
        return (
            <div>
                <Row>
                    <Form className="login-form">
                        <Row>
                            <Col span={7}>
                                <FormItem label="订单号" {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('output_num')(
                                            <Input type="text" placeholder="请输入"
                                                   onPressEnter={() => this.handleOnPressEnter()}/>
                                        )
                                    }
                                </FormItem>
                            </Col>
                            <Col span={7}>
                                <FormItem label="客户名" {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('customer_name')(
                                            <Input type="text" placeholder="请输入"
                                                   onPressEnter={() => this.handleOnPressEnter()}/>
                                        )
                                    }
                                </FormItem>
                            </Col>
                            <Col span={6}>
                                <FormItem label="状态" {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('output_status')(
                                            <Select placeholder="请选择"
                                                    onChange={(value) => this.handleStatusOnChange(value)}>
                                                <Option value='0'>待接单</Option>
                                                <Option value='1'>已接单</Option>
                                                <Option value='2'>配货中</Option>
                                                <Option value='3'>待对货</Option>
                                                <Option value='4'>待配送</Option>
                                                <Option value='5'>待改单</Option>
                                                <Option value='6'>配送中</Option>
                                                <Option value='7'>已完成</Option>
                                            </Select>
                                        )
                                    }
                                </FormItem>
                            </Col>
                            <Col span={4} style={{float: 'right'}}>
                                <Button type="primary"
                                        onClick={() => this.handleSearchComplain()}
                                >
                                    查询
                                </Button>
                                <Button type="default"
                                        onClick={() => this.handleReset()}
                                        style={{marginLeft: '10px'}}
                                >
                                    重置
                                </Button>
                            </Col>
                        </Row>
                        <Row>
                            <Col span={7}>
                                <FormItem label="下单日期" {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('order_time')(
                                            <RangePicker
                                                ranges={{
                                                    Today: [moment(), moment()],
                                                    'This Month': [moment(), moment().endOf('month')]
                                                }}
                                                format="YYYY/MM/DD"
                                                onChange={(dates, dateStrings) => this.handleOrderTimeOnChange(dates, dateStrings)}
                                            />
                                        )
                                    }
                                </FormItem>
                            </Col>
                            <Col span={7}>
                                <FormItem label="交货日期" {...this.formItemLayout}>
                                    {
                                        getFieldDecorator('delivery_time')(
                                            <RangePicker
                                                ranges={{
                                                    Today: [moment(), moment()],
                                                    'This Month': [moment(), moment().endOf('month')]
                                                }}
                                                format="YYYY/MM/DD"
                                                onChange={(dates, dateStrings) => this.handleDeliveryTimeOnChange(dates, dateStrings)}
                                            />
                                        )
                                    }
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                </Row>
            </div>
        )
    };

    componentDidMount() {

    };

    /**
     * 获取搜索条件
     */
    handleSearchComplain() {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.props.clickSearch(values);
            }
        })
    };

    /**
     * 处理重置按钮事件
     */
    handleReset() {
        this.props.form.resetFields();
        this.props.handleReset();
    };

    /**
     * 处理输入框按下回车键的事件
     */
    handleOnPressEnter() {
        //调用获取搜索条件的函数
        this.handleSearchComplain();
    };

    /**
     * 处理状态下拉框选择变化事件
     * @param value
     */
    handleStatusOnChange(value) {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                values.output_status = value;
                this.props.clickSearch(values);
            }
        })
    };

    /**
     * 处理实际来货日期选择框变化事件
     */
    handleDeliveryTimeOnChange(dates, dateStrings) {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                values.delivery_time = dates;
                this.props.clickSearch(values);
            }
        })
    };

    /**
     * 处理下单日期选择框变化事件
     */
    handleOrderTimeOnChange(dates, dateStrings) {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                values.order_time = dates;
                this.props.clickSearch(values);
            }
        })
    };
}

const SearchLists = Form.create()(SearchList);
const StorageManages = Form.create()(storageManage);
//export default storageManages;
export default prop => (
    <Consumer>
        {
            props => (
                <StorageManages {...prop} {...props} />
            )
        }
    </Consumer>
);